<?php
/**
 * @brief 环迅IPS支付插件类
 * @class Ips
 * @package App
 * @subpackage  Driver.Payment
 * @author cjli
 */
class Ips extends Payment implements Payment_Interface, Payment_Server_Interface
{
	public function __construct()
	{
		$this->_paymentInfo = PaymentModel::get_payment_info('Ips');
	}
	
  public function getSettingFields()
  {
    return array(
      'ips_account' => '商户帐号',
      'ips_key' => '商户密钥',
      'ips_currency' => array(
        'name' => '支付类型',
        'type' => 'select',
        'options' => array(
          '01' => '借记卡',
          '02' => '信用卡',
          '04' => 'IPS账户支付',
          '08' => 'I币支付',
          '16' => '电话支付',
        ),
        'default' => '01',
      ),
      'ips_lang' => array(
        'name' => '语言',
        'type' => 'select',
        'options' => array(
          'EN' => '英语',
          'GB' => '简体中文',
          'BIG5' => '繁体中文',
          'JP' => '日文',
          'FR' => '法文',
        ),
        'default' => 'GB',
      ),
    );
  }

  public function getSubmitForm($orderInfo)
  {
    $dateStr = date('Ymd', time());
    $orderNumber = $orderInfo['order_sn'];
    $orderAmount = $orderInfo['pay_amount'];
    
 	 	$c = SiteModel::get_currency_info('CNY');
		if (isset($c['exchange']) && $c['exchange']) {
		   $orderAmount = $c['exchange'] * $orderAmount;
		 }
		 
    $strcontent = $orderNumber . $orderAmount . $dateStr . 'RMB' . $this->_paymentInfo['config']['ips_key']; // 签名验证串 //
    $signmd5 = md5($strcontent);

    $html = array(
      '<form id="frm" action="https://pay.ips.com.cn/ipayment.aspx" method="post" target="_blank">',
// TODO the follow line just for testing, uncomment the above line instead the follow one.
//      '<form action="https://pay.ips.net.cn/ipayment.aspx" method="post" target="_blank">',
      '<input type="hidden" name="Mer_code" value="' . $this->_paymentInfo['config']['ips_account'] . '">',
      '<input type="hidden" name="Billno" value="' . $orderNumber . '">',
      '<input type="hidden" name="Gateway_type" value="' . $this->_paymentInfo['config']['ips_currency'] . '">',
      '<input type="hidden" name="Currency_Type" value="RMB">',
      '<input type="hidden" name="Lang" value="' . $this->_paymentInfo['config']['ips_lang'] . '">',
      '<input type="hidden" name="Amount" value="' . $orderAmount . '">',
      '<input type="hidden" name="Date" value="' . $dateStr . '">',
      '<input type="hidden" name="DispAmount" value="' . $orderAmount . '">',
      '<input type="hidden" name="OrderEncodeType" value="2">',
      '<input type="hidden" name="RetEncodeType" value="12">',
      '<input type="hidden" name="Rettype" value="1">',
      '<input type="hidden" name="Merchanturl" value="' . url('payment/callback', array('pay' => 'ips')) . '">',
      '<input type="hidden" name="FailUrl" value="' . url('') . '">',
      '<input type="hidden" name="ServerUrl" value="' . url('payment/notice', array('pay' => 'ips')) . '">',
// TODO http://113.108.143.212:8080 just for testing inside our office
//      '<input type="hidden" name="ServerUrl" value="' . ('http://113.108.143.212:8000' . url('payment/notice/ips', false)) . '">',
      '<input type="hidden" name="SignMD5" value="' . $signmd5 . '">',
      '<input type="submit" class="pay_button" value="' . L('_PAY_NOW_') . '">',
      '</form>',
    );
    return implode(PHP_EOL, $html);
  }

  private function checkGet()
  {
  	// 接收数据
        $pICPayRes = $_REQUEST['pICPayRes'];
        $pICPayRes = base64_decode($pICPayRes);
        $pICPayResHashValue = $_REQUEST['pICPayResHashValue'];
//        $payment = get_payment($_GET['code']);

        //签名验证
        if(md5($pICPayRes . 'Ips') == $pICPayResHashValue)
        {
            // 读取xml
            $xml = new DOMDocument();
            $xml->loadXML($pICPayRes);
			//$pMerchantOrderNum = $xml->getElementsByTagName('pMerchantOrderNum')->item(0)->nodeValue;
			//$pMerchantOrderNum = str_replace($payment['ips_icpay_prefix'] . '-', "", $pMerchantOrderNum); //剔除前缀
			//$order_sn = substr($pMerchantOrderNum, 0, strpos($pMerchantOrderNum, "-"));
            $_GET['payOrderNum'] = $xml->getElementsByTagName('pIPSOrderNum')->item(0)->nodeValue;
      //      $pResultCode = $xml->getElementsByTagName('pResultCode')->item(0)->nodeValue;
      //      $pBankMessage = urldecode($xml->getElementsByTagName('pBankMessage')->item(0)->nodeValue);
      //      $pDisplayAmount = urldecode($xml->getElementsByTagName('pDisplayAmount')->item(0)->nodeValue);
			//$pDisplayAmount = preg_replace('/[^\d.]/', '', $pDisplayAmount);
        }
    $succ = $_GET['succ'];
    $signmd5 = md5($_GET['billno'] . $_GET['amount'] . $_GET['date'] . $succ . $_GET['ipsbillno'] .
      $_GET['Currency_type'] . $this->_paymentInfo['config']['ips_key']);
    return $succ == 'Y' && $signmd5 == $_GET['signature'];
  }

  public function callback()
  {
    if ($this->checkGet()) {
      $result = array(
        'verified' => true,
        'paidAmount' => $_GET['amount'],
        'paymentId' => $_GET['ipsbillno'],
        'orderNumber' => $_GET['billno'],
      	'payOrderNum' => $_GET['payOrderNum'],
        'updateOrderStatus' => false,
        'message' => '',
      );
    } else {
      $result = array(
        'verified' => false,
      );
    }
    if($_GET['succ'] == 'Y'){
			$result['updateOrderStatus'] = true;
			$result['message'] = L('_PAYMENT_SUCCESS_');
		} else {
			$result['message'] = L('_PAYMENT_FAILURE_');
    }
    return $result;
  }

  public function serverCallback()
  {
    if ($this->checkGet()) {
      $result = array(
        'verified' => true,
        'paidAmount' => $_GET['amount'],
        'paymentId' => $_GET['ipsbillno'],
        'orderNumber' => $_GET['billno'],
      	'payOrderNum' => $_GET['payOrderNum'],
        'updateOrderStatus' => true,
        'message' => '',
      );
    } else {
      $result = array(
        'verified' => false,
      );
    }
    return $result;
  }
}
